package cn.itcast.flink.base;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * Author itcast
 * Date 2021/7/30 16:07
 * Desc TODO
 */
public class WordCountFlinkTable {
    public static void main(String[] args) throws Exception {
        //1.准备环境 获取流执行环境 流表环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //设置流表环境
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        //2.Source 获取 单词信息
        DataStream<WC> source = env.fromElements(
                new WC("Hello", 1),
                new WC("World", 1),
                new WC("Hello", 1),
                new WC("Hello", 2),
                new WC("Hello", 3)
        );
        //3.创建视图 WordCount
        //todo 创建表 Table
        Table wordTable = tEnv.fromDataStream(source, $("word"), $("frequency"));
        //todo 查看当前表结构
        wordTable.printSchema();
        //4.执行查询 单词统计
        //todo 通过Flink table api 来实现单词统计
        Table wordcountTable = wordTable.groupBy($("word"))
                .select($("word"), $("frequency").sum().as("frequency"))
                .as("word","frequency");
        //5.输出结果 retractStream获取数据流（别名）
        DataStream<Tuple2<Boolean, WC>> result = tEnv.toRetractStream(wordcountTable, WC.class);
        //6.打印输出结果
        result.print();
        //7.执行
        env.execute();
    }
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class WC {
        public String word;
        public long frequency;
    }
}
